package com.center.mapperscan;

import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.util.StringUtils;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author dzl
 * @Date 2022/1/20 10:12 上午
 * 手动注册我们的bean
 */
public class MyMapperScanImport implements ImportBeanDefinitionRegistrar {
    @Override
    public void registerBeanDefinitions(AnnotationMetadata annotationMetadata, BeanDefinitionRegistry beanDefinitionRegistry) {
        /*获取注解属性*/
        AnnotationAttributes attributes = AnnotationAttributes.fromMap(annotationMetadata.getAnnotationAttributes(MyMapperScan.class.getName()));
        /*bean构建*/
        BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(MyMapperScanConfig.class);
        assert attributes != null;
        List<String> scanBasePackages = Arrays.stream(attributes.getStringArray("scanBasePackages")).filter(StringUtils::hasText).collect(Collectors.toList());
        builder.addPropertyValue("scanBasePackages", StringUtils.collectionToCommaDelimitedString(scanBasePackages));
        beanDefinitionRegistry.registerBeanDefinition(MyMapperScanConfig.class.getName(), builder.getBeanDefinition());
    }
}
